package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.JobDto;
import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.UserToJobDto;
import com.dg.cuckoo.admin.repository.JobRepository;
import com.dg.cuckoo.admin.repository.UserToJobRepository;
import com.dg.cuckoo.admin.service.OrganizationService;
import com.dg.cuckoo.admin.service.UserToJobService;
import com.dg.cuckoo.admin.service.UsertoProjectService;
import com.dg.cuckoo.core.ServiceException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserToJobServiceimpl implements UserToJobService {

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private JobRepository jobRepository;
    @Autowired
    private UserToJobRepository userToJobRepository;


    @Override
    public String view() {
        String have = JSONObject.fromObject(organizationService.view()).getString("date");
        String no = JSONObject.fromObject(organizationService.view()).getString("list");

        List<JobDto> dtos = jobRepository.findAll();
        List<String> jobs=new ArrayList<>();
        for(JobDto j:dtos){
            jobs.add(j.getJob());
        }

        JSONObject json = new JSONObject();
        json.put("date",have);//用户名称树与数据
        json.put("list",no);//没有单位的用户
        json.put("jobs",jobs);//岗位
        return json.toString();
    }

    @Override
    public void save(String username, List<String> job) {
        if(username==null){
            throw new ServiceException("请选择用户");
        }
        if(job.size()>0){
            List<UserToJobDto> dtos = userToJobRepository.findUserToJobDtosByUsername(username);
            userToJobRepository.deleteAll(dtos);
            for(String s:job){
                UserToJobDto userToJobDto = new UserToJobDto();
                userToJobDto.setUsername(username);
                userToJobDto.setJob(s);
                userToJobRepository.save(userToJobDto);
            }
        }else {
            List<UserToJobDto> dtos = userToJobRepository.findUserToJobDtosByUsername(username);
            userToJobRepository.deleteAll(dtos);
        }
    }

    @Override
    public List<String> openUsernameInfo(String username) {
        List<UserToJobDto> dtos = userToJobRepository.findUserToJobDtosByUsername(username);
        List<String> list=new ArrayList<>();
        for(UserToJobDto u:dtos){
            list.add(u.getJob());
        }
        return list;
    }
}
